package com.itheima.auth;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private String type;

    private RequestCache requestCache = new HttpSessionRequestCache();

    //登录成功处理的方法
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        logger.info("登录成功");

        SavedRequest savedRequest = requestCache.getRequest(request, response);
        String targetUrl = null;
        if (savedRequest == null) {
            targetUrl = super.determineTargetUrl(request, response);
        } else {
            targetUrl = savedRequest.getRedirectUrl();
        }
        if ("json".equalsIgnoreCase(this.type) || "json".equalsIgnoreCase(request.getParameter("type"))) {
            response.setContentType("application/json;charset=UTF-8");

            response.getWriter().write("{\"message\":\"登录成功\",\"flag\":true}");

        } else {
            super.onAuthenticationSuccess(request, response, authentication);
        }

    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public void setRequestCache(RequestCache requestCache) {
        this.requestCache = requestCache;
    }

}
